<template>
  <div class="paper">
    <!-- 试卷列表 - 使用CSS Grid布局，包含新建试卷卡片 -->
    <div class="paper-grid">
      <!-- 新建试卷卡片 -->
      <div class="paper-card create-card" @click="createPaper">
        <div class="create-content">
          <div class="icon-container">
            <i class="fas fa-robot"></i>
          </div>
          <h3>AI智能组卷</h3>
          <p>使用AI技术快速生成高质量试卷</p>
        </div>
      </div>

      <!-- 普通试卷卡片 -->
      <div v-for="paper in filteredPapers" :key="paper.paperId" class="paper-card" @click="editPaper(paper)">
        <div class="card-gradient"></div>
        <!-- 添加删除按钮，只在未发布试卷上显示 -->
        <div v-if="paper.status === 0" class="delete-button" @click.stop="confirmDelete(paper)">
          <i class="fas fa-trash-alt"></i>
        </div>

        <div class="paper-header">
          <el-tooltip class="item" effect="light" :content="paper.paperName" placement="top">
            <h3>{{ paper.paperName }}</h3>
          </el-tooltip>
        </div>
        <div class="paper-meta">
          <div class="meta-item">
            <i class="fas fa-star"></i>
            <span>难度: {{ getDifficultyText(paper.avgDiffculty) }}</span>
          </div>
          <div class="meta-item">
            <i class="fas fa-clock"></i>
            <span>时长: {{ paper.timeLimit }}分钟</span>
          </div>
          <div class="meta-item">
            <i class="fas fa-check-circle"></i>
            <span>总分: {{ paper.totalScore }}分</span>
          </div>
          <div class="meta-item">
            <i :class="paper.status === 1 ? 'fas fa-paper-plane' : 'far fa-paper-plane'"></i>
            <span :class="{ 'status-published': paper.status === 1, 'status-unpublished': paper.status === 0 }">
              {{ paper.status === 1 ? '已发布' : '未发布' }}
            </span>
          </div>
        </div>
        <div class="paper-footer">
          <span>创建人: {{ getUserInfo.realName }}</span>
          <span>更新时间: {{ formatDate(paper.updatedAt) }}</span>
        </div>
        <div class="card-actions">
          <button class="btn-action btn-edit" @click.stop="editPaper(paper)">
            <i class="fas fa-edit"></i> 预览
          </button>
          <button class="btn-action btn-publish" @click.stop="togglePublish(paper)"
            :class="{ 'published': paper.status === 1 }" :disabled="paper.status === 1">
            <i :class="paper.status === 1 ? 'fas fa-check' : 'fas fa-paper-plane'"></i>
            {{ paper.status === 1 ? '发布成功' : '发布' }}
          </button>
        </div>
      </div>
    </div>

    <p v-if="noMore" class="end-of-list"> --- — 已经到底了 — --- </p>
  </div>
</template>

<script>
// 引入编辑模态框
import PaperEditorModal from '../components/paper/PaperEditorModal.vue';

// 引入AI创建试卷组件
import AIPaperGeneratorModal from "@/components/paper/AIPaperGeneratorModal.vue";

// 调用paper接口
import { getUserPapers as getUserPapersAPI, publishPapaer as publishPaperAPI } from "@/api/paper/index"

import { mapGetters } from 'vuex';

export default {
  name: 'PaperList',
  components: {
    PaperEditorModal,
    AIPaperGeneratorModal
  },
  data() {
    return {
      searchQuery: '',
      showEditor: false,
      selectedPaper: null,
      editorMode: 'create',
      currentUserId: 2,
      showAIPaperGenerator: false
    }
  },
  computed: {
    ...mapGetters('paper', [
      'getCheckedPaper',
      'getPapers',
      'getLoading',
      'getGenerateModelStatus',
      'getListParam',
      'getTotal'
    ]),
    ...mapGetters('user', [
      'getUserInfo'
    ]),
    total: {
      get() {
        return this.getTotal
      },
      set(value) {
        this.$store.commit('paper/setTotal', value)
      }
    },
    listParam: {
      get() {
        return this.getListParam
      },
      set(value) {
        this.$store.commit('paper/setListParam', value)
      }
    },
    filteredPapers() {
      if (!this.searchQuery) return this.papers;
      return this.papers.filter(paper =>
        paper.paper_name.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },
    // 计算属性获取vuex中的数据
    checkedPaper: {
      get() {
        return this.getCheckedPaper
      },
      set(value) {
        this.$store.commit('paper/setCheckedPaper', value)
      }
    },
    papers: {
      get() {
        return this.getPapers
      },
      set(value) {
        this.$store.commit('paper/setPapers', value)
      }
    },
    loading: {
      get() {
        return this.getLoading
      },
      set(value) {
        this.$store.commit('paper/setLoading', value)
      }
    },
    noMore() {
      return this.papers.length >= this.total;
    },
  },
  created() {
    // this.fetchPapers();
    this.$registerWebSocketHandler(this.handleMessage);
  },
  beforeDestroy() {
    // 组件销毁时移除回调，避免内存泄漏
    this.$unregisterWebSocketHandler(this.handleMessage);
  },
  methods: {
    // 处理websocket发送来的消息的方法
    handleMessage(message) {
      // if(message.messageType == 1){
      //   this.fetchPapers();
      // }else if(message.messageType == 2){
      //   this.editPaper(this.papers[0]);
      // }
      // 根据 message 内容做对应处理
    },
    // 发送websocket消息的方法
    send() {
      this.$websocket.sendMessage({ content: "hello" });
    },
    // async fetchPapers() {
    //   this.loading = true;
    //   try {
    //     let res = await getUserPapersAPI();
    //     let {data} = res.data;
    //     this.papers = data;

    //   } catch (error) {
    //     console.error('获取试卷数据失败:', error);
    //   } finally {
    //     this.loading = false;
    //   }
    // },
    getDifficultyText(level) {
      const levels = ['容易', '容易', '容易', '中等', '中等', '中等', '中等', '困难', '困难', '困难'];
      return levels[level - 1] || '未知';
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    handleSearch() {
      // 搜索逻辑已在计算属性中处理
    },
    createPaper() {
      this.$store.commit('paper/setGenerateModelStatus', true);
    },
    editPaper(paper) {
      this.$router.push("/paper-index/editor")
      this.checkedPaper = paper;
    },
    handleSavePaper(paper) {
      if (this.editorMode === 'create') {
        const newPaper = {
          ...paper,
          paperId: Math.max(...this.papers.map(p => p.paperId)) + 1,
          userId: this.currentUserId,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        };
        this.papers.unshift(newPaper);
      } else {
        const index = this.papers.findIndex(p => p.paperId === paper.paperId);
        if (index !== -1) {
          this.papers.splice(index, 1, {
            ...this.papers[index],
            ...paper,
            updatedAt: new Date().toISOString()
          });
        }
      }
      this.showEditor = false;
    },
    async togglePublish(paper) {
      try {
        await this.$confirm(
          '试卷发布后无法取消发布或删除，是否确认发布？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );

        if (paper.status === 0) {
          const index = this.papers.findIndex(p => p.paperId === paper.paperId);

          const params = {
            paperId: paper.paperId,
            examName: paper.paperName,
            type: "其它"
          };

          try {
            await publishPaperAPI(params);

            if (index !== -1) {
              this.papers.splice(index, 1, {
                ...this.papers[index],
                status: 1,
                updatedAt: new Date().toISOString()
              });
            }
          } catch (error) {
            this.$message.error('发布试卷失败，请稍后重试');
          }
        }
      } catch (e) {
        // 用户点击了取消按钮
        // console.log('取消发布操作');
      }
    },
    closeAIPaperGenerator() {
      this.showAIPaperGenerator = false;
    },
    async confirmDelete(paper) {
      try {
        await this.$confirm(
          `确定要删除试卷"${paper.paperName}"吗？删除后无法恢复。`,
          '删除确认',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'error',
            confirmButtonClass: 'el-button--danger'
          }
        );

        try {
          // 使用store的action删除试卷
          await this.$store.dispatch('paper/deletePaper', paper.paperId);
          this.$message.success('试卷删除成功');
        } catch (error) {
          this.$message.error('删除试卷失败，请稍后重试');
          console.error('删除试卷失败:', error);
        }
      } catch (e) {
        // 用户取消删除操作
      }
    }
  }
}
</script>

<style lang="less" scoped>
@primary: #4361EE;
@primary-light: #A5B4FC;
@secondary: #3A0CA3;
@success: #10B981;
@warning: #F59E0B;
@gray-100: #F3F4F6;
@gray-200: #E5E7EB;
@gray-300: #D1D5DB;
@gray-400: #9CA3AF;
@gray-500: #6B7280;
@gray-600: #4B5563;
@gray-700: #374151;
@gray-800: #1F2937;
@gray-900: #111827;
@danger: #DC2626;

@shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
@shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
@radius-sm: 0.375rem;
@radius-md: 0.5rem;
@radius-lg: 0.75rem;
@transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

.paper {
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 1rem;
  background-color: @gray-100;

  /* 新建试卷卡片 */
  .create-card {

    margin: 10px;

    &::after {
      content: 'NEW';
      position: absolute;
      top: 10px;
      right: -30px;
      width: 100px;
      padding: 0.25rem 0;
      background: @warning;
      color: white;
      font-size: 0.75rem;
      font-weight: bold;
      text-align: center;
      transform: rotate(45deg);
    }
  }
}

/* 试卷网格布局 */
.paper-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1rem;
  padding: 0 10px;
}

.paper-card {
  background: white;
  border-radius: @radius-lg;
  padding: 1.5rem;
  box-shadow: @shadow-sm;
  transition: @transition;
  cursor: pointer;
  border: 1px solid @gray-200;
  display: flex;
  flex-direction: column;
  height: 300px;
  box-sizing: border-box;
  position: relative;
  margin: 10px;

  .card-gradient {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 5px;
    background: linear-gradient(90deg, @primary, @secondary);
    opacity: 0.9;
    transition: @transition;
    border-top-left-radius: @radius-lg;
    border-top-right-radius: @radius-lg;
  }

  /* 删除按钮样式 */
  .delete-button {
    position: absolute;
    top: 24px;
    right: 24px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    color: @gray-500;
    opacity: 0;
    /* 默认隐藏 */
    transition: @transition;
    z-index: 10;
    box-shadow: @shadow-sm;
    font-size: 12px;

    &:hover {
      background-color: @danger;
      color: white;
      transform: scale(1.1);
    }
  }

  &:hover .delete-button {
    opacity: 1;
    /* 悬停时显示 */
  }

  &:hover {
    transform: translateY(-3px);
    box-shadow: @shadow-md;
    border-color: @primary-light;
  }

  &.create-card {
    background: linear-gradient(135deg, rgba(@primary, 0.1), rgba(@secondary, 0.1));
    border: 2px dashed rgba(@primary, 0.3);
    align-items: center;
    justify-content: center;
    height: 300px;
    overflow: hidden;

    .create-content {
      text-align: center;
      color: @primary;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;

      .icon-container {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background-color: @primary;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 15px;

        i {
          color: white;
          font-size: 28px;
          margin: 0;
        }
      }

      h3 {
        margin: 0.5rem 0;
        font-weight: 600;
        color: @primary;
        font-size: 20px;
      }

      p {
        margin: 0;
        font-size: 14px;
        color: @gray-600;
      }
    }

    &:hover {
      background: linear-gradient(135deg, rgba(@primary, 0.15), rgba(@secondary, 0.15));
      border-color: @primary;

      .icon-container {
        transform: scale(1.1);
      }
    }
  }

  .paper-header {
    margin-bottom: 1rem;

    h3 {
      margin: 0;
      width: 100%;
      font-size: 1.125rem;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color: @gray-800;
    }
  }

  .paper-meta {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, auto);
    gap: 0.75rem;
    margin-bottom: 1.5rem;

    .meta-item {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      font-size: 0.875rem;
      color: @gray-600;

      i {
        color: @gray-500;
        width: 16px;
        text-align: center;
      }

      .status-published {
        color: @success;
        font-weight: 500;
      }

      .status-unpublished {
        color: @gray-500;
        font-weight: 500;
      }
    }
  }

  .paper-footer {
    display: flex;
    justify-content: space-between;
    font-size: 0.8125rem;
    color: @gray-500;
    padding-top: 1rem;
    border-top: 1px solid @gray-200;
    margin-top: auto;
  }

  .card-actions {
    display: flex;
    gap: 0.5rem;
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid @gray-200;

    .btn-action {
      flex: 1;
      padding: 0.5rem;
      border-radius: @radius-sm;
      font-size: 0.75rem;
      font-weight: 500;
      cursor: pointer;
      transition: @transition;
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.25rem;

      &.btn-edit {
        background: @gray-100;
        color: @gray-700;

        &:hover {
          background: @gray-200;
        }
      }

      &.btn-publish {
        background: rgba(@primary, 0.1);
        color: @primary;

        &:hover {
          background: rgba(@primary, 0.2);
        }

        &.published {
          background: rgba(@success, 0.1);
          color: @success;

          &:hover {
            background: rgba(@success, 0.2);
          }
        }
      }
    }
  }
}

/* 底部提示信息 */
.end-of-list {
  position: absolute;
  left: 50%;
  bottom: -50px;
  transform: translateX(-50%);
  margin: 1rem 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .paper-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
}

@media (max-width: 480px) {
  .paper-grid {
    grid-template-columns: 1fr;
  }
}
</style>